﻿using Microsoft.SharePoint.Client;
using SPClientAdmin.Core.Common.Exceptions;

namespace SPClientAdmin.Core.SPModel
{
    /// <summary>
    /// Handle a user on SharePoint
    /// </summary>
    public class ClientUser
    {
        /// <summary>
        /// Contains the context object of the client connexion
        /// </summary>
        protected ClientContext Context;
        /// <summary>
        /// Contains the user client object
        /// </summary>
        protected User UserObject;

        /// <summary>
        /// Get the user's user name
        /// </summary>
        public string UserName { get { return UserObject.LoginName; } }
        /// <summary>
        /// Get and set the user's email (need to call update to be updated)
        /// </summary>
        public string UserEmail { get { return UserObject.Email; } set { UserObject.Email = value; } }

        /// <summary>
        /// Create a new user handler
        /// </summary>
        /// <param name="user">Client model user object</param>
        internal ClientUser(User user)
        {
            Context = user.Context as ClientContext;
            UserObject = user;
        }
        
        /// <summary>
        /// Update on the server the modifications that have been made on the user
        /// </summary>
        public void Update()
        {
            try
            {
                UserObject.Update();
                Context.ExecuteQuery();
            }
            catch(ServerException)
            {
                //TODO : Trace exception and handle according to server error code
                throw new UnableToUpdateUserException(UserName);
            }

        }
    }
}
